package com.example.opengldemo.simple12_04;

import android.opengl.GLES30;
import android.opengl.GLSurfaceView;
import android.view.MotionEvent;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.view.View;

import com.example.opengldemo.util.LoadUtil;
import com.example.opengldemo.util.MatrixState;

class MySurfaceView extends GLSurfaceView {
	private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
	private SceneRenderer mRenderer;

	private float mPreviousY;
	private float mPreviousX;

	public MySurfaceView(Context context) {
		super(context);
		this.setEGLContextClientVersion(3);
		mRenderer = new SceneRenderer();
		setRenderer(mRenderer);
		setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
	}


	@Override
	public boolean onTouchEvent(MotionEvent e) {
		float y = e.getY();
		float x = e.getX();
		switch (e.getAction()) {
		case MotionEvent.ACTION_MOVE:
			float dy = y - mPreviousY;
			float dx = x - mPreviousX;
			mRenderer.yAngle += dx * TOUCH_SCALE_FACTOR;
			mRenderer.xAngle += dy * TOUCH_SCALE_FACTOR;
			requestRender();
		}
		mPreviousY = y;
		mPreviousX = x;
		return true;
	}

	private class SceneRenderer implements Renderer {
		float yAngle;
		float xAngle;
		float countE = 0;
		float spanE = 0.01f;

		LoadedObjectVertexNormal lovo;

		public void onDrawFrame(GL10 gl) {
			if (countE >= 2) {
				spanE = -0.01f;
			} else if (countE <= 0) {
				spanE = 0.01f;
			}
			countE = countE + spanE;
			float e[] = { 1, countE - 1, -countE + 1, 0 };

			GLES30.glClear(GLES30.GL_DEPTH_BUFFER_BIT
					| GLES30.GL_COLOR_BUFFER_BIT);
			MatrixState.pushMatrix();
			MatrixState.translate(0, -2f, -25f);
			MatrixState.rotate(yAngle, 0, 1, 0);
			MatrixState.rotate(xAngle, 1, 0, 0);			
			if (lovo != null) {
				lovo.drawSelf(e);
			}
			MatrixState.popMatrix();
		}

		public void onSurfaceChanged(GL10 gl, int width, int height) {
			GLES30.glViewport(0, 0, width, height);
			float ratio = (float) width / height;
			MatrixState.setProjectFrustum(-ratio, ratio, -1, 1, 2, 100);
			MatrixState.setCamera(0, 0, 0, 0f, 0f, -1f, 0f, 1.0f, 0.0f);
		}

		public void onSurfaceCreated(GL10 gl, EGLConfig config) {
			GLES30.glClearColor(0.3f, 0.3f, 0.3f, 1.0f);
			GLES30.glEnable(GLES30.GL_DEPTH_TEST);
			GLES30.glEnable(GLES30.GL_CULL_FACE);
			MatrixState.setInitStack();
			MatrixState.setLightLocation(40, 10, 20);
			LoadUtil.getLoadObj(MySurfaceView.this, "simple12_04/zh.obj",
					new LoadUtil.CreateObjectLoader() {
						@Override
						public void create(View view, float[] vertexArray, float[] normalArray, float[] texcoorsArray) {
							lovo = new LoadedObjectVertexNormal(view , vertexArray , normalArray ) ;
						}
					});
		}
	}
}
